package io.gitee.kotle.android.mvvm

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout

/**
 *
 * 描述：
 *
 * @author jiale.wei
 *
 * 创建时间：2022/7/14 12:27
 *
 */
open class DialogRootLayout : FrameLayout {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private val bounds = RectF()
    private var canDismissWhenDown = false

    open var dialog: Dialog? = null
    open var dialogView: View? = null

    open var isCancelable = true
    open var isCanceledOnTouchOutside = true

    /**
     * 不用点击事件处理是防止点击穿透
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                canDismissWhenDown = checkCanDismiss(ev)
            }
            MotionEvent.ACTION_UP -> {
                if (canDismissWhenDown && checkCanDismiss(ev)) {
                    dialog?.dismiss()
                }
            }
            else -> {
            }
        }
        return true
    }

    private fun checkCanDismiss(ev: MotionEvent): Boolean {
        val view = dialogView
        if (view == null) {
            if (isCancelable && isCanceledOnTouchOutside) {
                return true
            }
        } else {
            bounds.set(
                view.left.toFloat(),
                view.top.toFloat(),
                view.right.toFloat(),
                view.bottom.toFloat()
            )
            if (!bounds.contains(ev.x, ev.y)) {
                if (isCancelable && isCanceledOnTouchOutside) {
                    return true
                }
            }
        }
        return false
    }
}